import React, { memo, useEffect, useState, useContext } from "react";
import { NsTreeContext, NsTreeContextData } from "@pkgs/Layout/Provider";
import CreateIncludeNsTree from "@pkgs/Layout/CreateIncludeNsTree";
import useFormatMessage from "@pkgs/hooks/useFormatMessage";
import { Icon, message, Tabs, Tooltip } from "antd";
import Improved from "./Improved";
import EnvEvent from "./EnvEvent";
import request from "@pkgs/request";
import api from "@common/api";
import _ from "lodash";
import "./style.less";

type Props = {
  history: API.History;
  match: API.Match;
  location: API.Location;
};

const { TabPane } = Tabs;

const EnvOverview: React.FC<Props> = (props) => {
  const [keywords, setKeywords] = useState<string>("");
  const intlFormatMsg = useFormatMessage();

  const context: NsTreeContextData = useContext(NsTreeContext);

  const { selectedNode } = context.data;

  const nodeStatus = (keywords: string) => {
    const keywordsLen = keywords.split(".").length;
    if (keywordsLen <= 2) {
      message.warning("1/2级节点没有环境监控");
    } else {
      setKeywords(keywords);
    }
  };

  useEffect(() => {
    if (selectedNode) {
      let nodePath = selectedNode.path;
      const node = selectedNode.id;
      if (nodePath) {
        nodeStatus(nodePath);
      } else {
        request(`${api.node}/${node}`).then((res) => {
          nodePath = res.path;
          nodeStatus(nodePath);
        });
      }
    }
  }, [selectedNode]);

  return (
    <>
      <header className="env-overview-header">
        <Tabs type="card">
          <TabPane tab={intlFormatMsg({ id: "env.improved" })} key="1">
            <Improved keywords={keywords} />
          </TabPane>
          <TabPane
            tab={
              <Tooltip
                placement="topLeft"
                title={<span>{intlFormatMsg({ id: "env.event.prompt" })}</span>}
              >
                {intlFormatMsg({ id: "env.event" })}&nbsp;
                <Icon
                  type="exclamation-circle"
                  style={{
                    fontSize: "11px",
                    position: "absolute",
                    top: '4px'
                  }}
                />
              </Tooltip>
            }
            key="2"
          >
            <EnvEvent keywords={keywords} />
          </TabPane>
        </Tabs>
      </header>
    </>
  );
};

export default memo(CreateIncludeNsTree(EnvOverview, { visible: true }));
